# !/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time : 2022/6/5 14:57
# @Author : xyjiang1216
# @Email : jiangxuyan@nudt.edu.cn
# @File : fwd_tbl_structure.py
# @Version: planner_builder 1.0

import ctypes
from tsn_builder_struct.table_length import *

c_uint32 = ctypes.c_uint32


# 转发表表项的详细字段组成
class FwdModeEntry_bits(ctypes.BigEndianStructure):
    _fields_ = [
        # entry1
        ('valid', c_uint32, 1),
        ('reserve', c_uint32, 31),
        # entry2
        ('forward_mode', c_uint32, 32)
    ]


# 组织成32bit数据的转发表表项
class FwdModeEntry_bytes(ctypes.BigEndianStructure):
    _fields_ = [
        ('entry1', c_uint32, 32),
        ('entry2', c_uint32, 32)
    ]


# 转发表表项联合体
class FwdModeEntry_union(ctypes.Union):
    _fields_ = [
        ("bit", FwdModeEntry_bits),
        ("byte", FwdModeEntry_bytes)
    ]


# 转发表表项
class FwdModeEntry:
    def __init__(self,
                 fwd_mode_entry: FwdModeEntry_union):
        self.fwd_mode_entry = fwd_mode_entry


# 一个节点上的转发表
class FwdModeTblEachNode:
    def __init__(self,
                 node_id: int) -> None:
        self.node_id = node_id
        self.tbl_len = FWD_MODE_TBL_LEN
        self.entry_cnt = 0
        # 转发表的默认表项为空
        self.tbl_each_node = [FwdModeEntry(None)
                              for i in range(self.tbl_len)]

    def append_entry(self,
                     entry: FwdModeEntry) -> None:
        if self.entry_cnt < self.tbl_len:
            self.tbl_each_node[self.entry_cnt] = entry
            self.entry_cnt += 1
        else:
            print('The number of fwd_mode entries exceeds '
                  'the hardware limit, please check the fwd_mode_xml')
            print('node_id: %d' % self.node_id)
            exit(0)


class FwdModeTbl:
    def __init__(self):
        self.tbl_set = []

    def append_tbl(self,
                   tbl: FwdModeTblEachNode) -> None:
        self.tbl_set.append(tbl)
